import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.ResourceBundle;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

/**
 * A Servlet to help view jpg images
 *
 * @author James Chy
 */

public class PhotoServlet extends HttpServlet {

    String initpath;
    String title;
    ResourceBundle rb;
    boolean showQuery;
    PrintWriter out;
/*
    ResultSet rs;
*/
    String connection;
    String start, thumbs, oversize;
    double thumbsize;

    String maxresults, imgmain, imgthmb;
    String imgover, printsize, printrows;
    String printwide, printurl, printdir;
    String iuimages, iuthumbs, results;
    boolean maintpeople, maintthings, maintplaces, savefiles; 
    boolean maintdates, updatebtn, updatethumb;
    boolean additems, canfindnew;
    
    static final long serialVersionUID = 0;
    
    public ResultSet executeQuery(String query)
    {
        ResultSet rs=null;
        try
        {
            Class.forName("org.gjt.mm.mysql.Driver").newInstance();
            java.sql.Connection conn;
            conn = DriverManager.getConnection(connection);
            Statement stmt;

            stmt=conn.createStatement();
                  
            rs = stmt.executeQuery(query);

            //conn.close();
 
        }
        catch(ClassNotFoundException cnfe)
        {
            out.println("Class Not Found Exception "+cnfe.getMessage().toString());
        }
        
        catch(InstantiationException ie)
        {
            out.println("Instantiation Exception "+ie.toString());
        }        
        catch(IllegalAccessException iae)
        {
            out.println("Illegal Access Exception "+iae.toString());
        }
        catch(SQLException sqle)
        {
            out.println("SQL Exception "+sqle.toString());
        }

        return rs;
    }

    public int executeUpdate(String query)
    {
        int result=-1;

        try
        {
            Class.forName("org.gjt.mm.mysql.Driver").newInstance();
            java.sql.Connection conn;
            conn = DriverManager.getConnection(connection);
            Statement stmt;

            stmt=conn.createStatement();

            result = stmt.executeUpdate(query);

            conn.close();

        }
        catch(ClassNotFoundException cnfe)
        {
            out.println("Class Not Found Exception "+cnfe.getMessage().toString());
        }

        catch(InstantiationException ie)
        {
            out.println("Instantiation Exception "+ie.toString());
        }
        catch(IllegalAccessException iae)
        {
            out.println("Illegal Access Exception "+iae.toString());
        }
        catch(SQLException sqle)
        {
            out.println("SQL Exception "+sqle.toString());
        }

        return result;
    }

    public void init(ServletConfig config) throws ServletException
    {
        super.init(config);
        rb = ResourceBundle.getBundle("Environment");
        connection  = rb.getString("servletAlbum.connection");
        start       = rb.getString("servletAlbum.start");
        thumbs      = rb.getString("servletAlbum.thumbs");
        oversize    = rb.getString("servletAlbum.oversize");
        thumbsize   = Double.parseDouble(rb.getString("servletAlbum.thumbsize"));
        iuimages    = rb.getString("imgupdate.images");
        iuthumbs    = rb.getString("imgupdate.thumbs");
        maxresults  = rb.getString("servletAlbum.maxresults");
        imgmain     = rb.getString("servletAlbum.imgmain");
        imgthmb     = rb.getString("servletAlbum.imgthmb");
        imgover     = rb.getString("servletAlbum.imgover");
        printsize   = rb.getString("servletAlbum.printsize");
        printrows   = rb.getString("servletAlbum.printrows");
        printwide   = rb.getString("servletAlbum.printwide");
        printurl    = rb.getString("servletAlbum.printurl");
        printdir    = rb.getString("servletAlbum.printdir");
        results     = rb.getString("servletAlbum.results");
        rb = ResourceBundle.getBundle("LocalStrings");
        showQuery   = rb.getString("servletAlbum.showQuery").equals("yes");
        title       = rb.getString("servletAlbum.title");
        additems    = rb.getString("servletAlbum.additems").equalsIgnoreCase("yes");
        canfindnew  = rb.getString("servletAlbum.canfindnew").equalsIgnoreCase("yes");
        maintdates  = rb.getString("servletAlbum.maintdates").equalsIgnoreCase("yes");
        maintpeople = rb.getString("servletAlbum.maintpeople").equalsIgnoreCase("yes");
        maintplaces = rb.getString("servletAlbum.maintplaces").equalsIgnoreCase("yes");
        maintthings = rb.getString("servletAlbum.maintthings").equalsIgnoreCase("yes");
        savefiles   = rb.getString("servletAlbum.savefiles").equalsIgnoreCase("yes"); 
        updatebtn   = rb.getString("servletAlbum.updatebtn").equalsIgnoreCase("yes");
        updatethumb = rb.getString("servletAlbum.updatethumb").equalsIgnoreCase("yes");
        
    }
    
	public static String MonthDayYear(String inYearMonthDay)
	{
		String result = inYearMonthDay;
		
		if(inYearMonthDay.length() == 8 && PhotoServlet.isNumeric(inYearMonthDay))
			result = inYearMonthDay.substring(4,6) + "/" +
			         inYearMonthDay.substring(6,8) + "/" +
			         inYearMonthDay.substring(0,4);
		
		return result;
	}
	
	private static boolean isNumeric(String inString)
	{
		boolean result = true;
		char[] charArray =  inString.toCharArray();
		
		for(int i=0; i< inString.length(); i++)
			if(charArray[i] < '0' || charArray[i] > '9')
				result = false;
		
		return result;
	}
	
	public static String GetModifiedDateYearMonthDay(File inFile)
	{
		String result = "";
		
		long modifiedLong = inFile.lastModified();
		
		GregorianCalendar modifiedGC = new GregorianCalendar();
		
		modifiedGC.setTimeInMillis(modifiedLong);
		
		if(modifiedGC != null)
		{
			int iYear = modifiedGC.get(Calendar.YEAR);
			int iMonth = modifiedGC.get(Calendar.MONTH);
			int iDay = modifiedGC.get(Calendar.DAY_OF_MONTH);
			String sYear = "";
			String sMonth = "";
			String sDay = "";
			if(iYear == 0)
				sYear = "0000";
			else if(iYear < 10)
				sYear = "000" + String.valueOf(iYear);
			else if(iYear < 100)
				sYear = "00" + String.valueOf(iYear);
			else if(iYear < 1000)
				sYear = "0" + String.valueOf(iYear);
			else sYear = String.valueOf(iYear);
			
			if(iMonth+1 == 0)
				sMonth = "00";
			else if(iMonth+1 < 10)
				sMonth = "0" + String.valueOf(iMonth+1);
			else sMonth = String.valueOf(iMonth+1);

			if(iDay == 0)
				sDay = "00";
			else if(iDay < 10)
				sDay = "0" + String.valueOf(iDay);
			else sDay = String.valueOf(iDay);

			result = sYear + sMonth + sDay;
		}
		return result;
		
	}
	
	/**
	 * 
	 * @param start
	 * @param offset
	 * @return String[]
	 * 
	 *         RecursiveList works like File.list except it recursively
	 *         traverses subdirectories removing those subdirectories from the
	 *         resulting list.
	 * 
	 *         start should not have a trailing separator and offset should have
	 *         neither a leading nor a trailing separator.
	 * 
	 */
	public static String[] recursiveList(String start, String offset) {

		String[] items, currSubItems, result;
		ArrayList<String> allSubItems, subDirs, resultArrayList;
		File item, fileDirectory;
		String nextOffset;

		currSubItems = new String[0];
		allSubItems = new ArrayList<String>();
		subDirs = new ArrayList<String>();
		if (offset.equals(""))
			fileDirectory = new File(start);
		else
			fileDirectory = new File(start + File.separator + offset);

		if (fileDirectory.isDirectory()) {

			items = fileDirectory.list();

			for (int i = 0; i < items.length; i++) {
				if (offset.equals(""))
					nextOffset = items[i];
				else
					nextOffset = offset + File.separator + items[i];
				item = new File(start + File.separator + nextOffset);
				if (item.isDirectory()) {
					currSubItems = recursiveList(start, nextOffset);
					for (int j = 0; j < currSubItems.length; j++)
						allSubItems.add(currSubItems[j]);
					subDirs.add(items[i]);
				}
			}

			resultArrayList = new ArrayList<String>();
			for (int i = 0; i < items.length; i++) {
				if (!subDirs.contains(items[i])) {
					if (offset.equals(""))
						resultArrayList.add(items[i]);
					else
						resultArrayList.add(offset + File.separator + items[i]);
				}
			}
			resultArrayList.addAll(allSubItems);

			result = new String[resultArrayList.size()];
			result = resultArrayList.toArray(result);
		} else
			result = null;

		return result;

	}

	/**
	 * 
	 * @param Source File File
	 * @param Destination File
	 * @return Boolean - whether the file was copied or not
	 */
	public static boolean copyfile(String srFile, String dtFile) {

		boolean result = true;

		try {
			File f1 = new File(srFile);
			File f2 = new File(dtFile);
			InputStream in = new FileInputStream(f1);

			OutputStream out = new FileOutputStream(f2);

			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
		} catch (FileNotFoundException ex) {
			result = false;
		} catch (IOException e) {
			result = false;
		}

		return result;
	}	
	
	public static String LastNameFirst(ResultSet rs) 
	throws SQLException
	{
		String value;
		
		String firstName=rs.getString("firstName");
		String middleName=rs.getString("middleName");
		String lastName=rs.getString("lastName");
		String suffix=rs.getString("suffix");
		
		if(lastName.equals(""))
			value = firstName + " " + middleName;    
		else
			value = lastName + ", " + firstName + " " + middleName;    
		if(!suffix.equals(""))
			value=value+", " + suffix;
		
		return value;
	}
	
	public static String FullName(ResultSet rs) 
	throws SQLException
	{
		String value;
		
		String firstName=rs.getString("firstName");
		String middleName=rs.getString("middleName");
		String lastName=rs.getString("lastName");
		String maidenName=rs.getString("maidenName");
		String suffix=rs.getString("suffix");
		
		if(lastName.equals("") && middleName.equals(""))
			value=firstName;
		else if(middleName.equals(""))
			value = firstName + " " + lastName;    
		else
			value = firstName + " " + middleName + " " + lastName; 
		if(!suffix.equals(""))
			value=value+", "+suffix;
		if(!maidenName.equals(""))
			value=value+" (nee "+maidenName+")";
		return value;
	}
	
	public static String FirstNameLastName(ResultSet rs) 
	throws SQLException
	{
		String value;
		
		String firstName=rs.getString("firstName");
		String lastName=rs.getString("lastName");
		String suffix=rs.getString("suffix");
		
		if(lastName.equals(""))
			value=firstName;
		else 
			value = firstName + " " + lastName;    
		
		if(!suffix.equals(""))
			value=value+", "+suffix;
		return value;
	}	

}